package com.mengxin.secondkill.config;

import com.mengxin.secondkill.exception.ServiceException;
import com.mengxin.secondkill.message.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.io.File;

/**
 * @author mengxin
 * @date 2020/12/12 17:41
 */
@Slf4j
@RestControllerAdvice
public class ExceptionHandleConfig implements ResponseBodyAdvice<Object> {

    @ExceptionHandler(ServiceException.class)
    public Result<Object> serviceException(ServiceException serviceException){
        log.error(serviceException.getMessage());
        return new Result<>(serviceException);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result<Object> illegalArgumentException(IllegalArgumentException illegalArgumentException){
        log.error(illegalArgumentException.getMessage());
        return new Result<>(illegalArgumentException);
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Result || body instanceof String) {
            return body;
        } else if (body instanceof File) {
            return body;
        } else {
            Result<Object> result = new Result<>(body);
            return result;
        }
    }
}
